import java.util.ArrayList;
import java.util.List;


class Solution {
    //暴力解法
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        int m = mat.length;
        int n = mat[0].length;
        if (m * n != r * c) return mat;
        int [][] arr = new int[r][c];
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                list.add(mat[i][j]);
            }
        }
        int k = 0;
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                arr[i][j] = list.get(k);
                k++;
            }
        }
        return arr;
    }
    //巧妙解法：
    public int[][] matrixReshape2(int[][] nums, int r, int c) {
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }

        int[][] ans = new int[r][c];
        //二维数组共有mn个元素，对于x∈[0,mn)，第x个元素在nums中对应的下标为[x/n][x%n]
        // 而在新的重塑矩阵中对应的下标为[x/c][x%c]
        for (int x = 0; x < m * n; ++x) {
            ans[x / c][x % c] = nums[x / n][x % n];
        }
        return ans;
    }

}